<template>
  <div class="view-fill">
    <div
      v-if="!maintenanceOrderDetailInfo.visible && !modifyInfo.visible"
      class="app-container-flex"
    >
      <FullScreen
        v-model="showDialog"
        :btn-list="btnList"
        :title="title"
        :needReturn="props.flowFormType ? false : true"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <el-button v-if="canExcel" @click="exportExcel">导出excel</el-button>
          <el-button v-if="canReminder" @click="reminder">催单</el-button>
          <el-button v-if="canSendOrder" @click="sendOrder">派单</el-button>
          <el-button v-if="canUpdateSendOrder" @click="updateSendOrder"
            >改派</el-button
          >
          <el-button v-if="canHandleRegister" @click="handleRegister"
            >处理登记</el-button
          >
          <el-button v-if="canFinish" @click="finish">完工</el-button>
          <el-button v-if="canTransfer" @click="transfer">院外报修</el-button>
          <el-button v-if="canEstimate" @click="estimate">评价</el-button>
          <el-button v-if="canCancelFinish" @click="cancelFinish"
            >取消完工</el-button
          >
          <el-button @click="edit" v-if="canEdit">修改</el-button>
          <el-button v-if="canRevoke" @click="revoke">撤销</el-button>
          <el-button @click="recall" v-if="canRecall">撤回</el-button>
          <el-button @click="btnFlow('approve')" v-if="canAccept"
            >批准</el-button
          >
          <el-button @click="btnFlow('reject')" v-if="canReject"
            >驳回</el-button
          >
          <el-button @click="btnFlow('refuse')" v-if="canRefuse"
            >拒绝</el-button
          >
          <el-button @click="stopInfo" v-if="canStopInfo">中止</el-button>
          <el-button @click="salesReview" v-if="canSalesReview">销审</el-button>
          <el-button @click="submit" v-if="canSubmit">提交</el-button>
        </template>

        <div class="model-panel model-panel-left">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="baseInfoList"></basic-information>
          </div>
        </div>

        <div class="model-panel model-panel-left">
          <div class="model-panel-title">
            <p>报修信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList">
              <template v-slot:basic-filePathList>
                <UploadVideo
                  v-if="repairInfoList.data.filePathList"
                  :fileData="repairInfoList.data.filePathList"
                  :uploadDisabled="false"
                />
                <span v-else> - </span>
              </template>
            </basic-information>
          </div>
        </div>
        <div class="model-panel model-panel-left">
          <div class="model-panel-title">
            <p>鉴定意见</p>
          </div>
          <div class="model-panel-body">
            <!-- <basic-information :info="repairPriceInfoList"></basic-information> -->
            <basic-information
              v-model:refObj="repairPriceSlotInfoList.ref"
              :rules="repairPriceSlotInfoList.rules"
              :info="repairPriceSlotInfoList"
              style="margin-bottom: 16px"
            >
              <template v-slot:basic-estimateAmount>
                <el-input-number
                  v-model="repairPriceSlotInfoList.data.estimateAmount"
                  :disabled="!canFlowEdit"
                  :min="0"
                  :max="99999999"
                  controls-position="right"
                  placeholder="请输入维修服务费"
                ></el-input-number>
              </template>
              <template v-slot:basic-appraisalContent>
                <el-input
                  v-model="repairPriceSlotInfoList.data.appraisalContent"
                  type="textarea"
                  :rows="1"
                  :disabled="!canFlowEdit"
                  controls-position="right"
                  :maxlength="500"
                  placeholder="请输入鉴定内容"
                ></el-input>
              </template>
            </basic-information>
            <PageFilter :filter-list="filterInfo.list">
              <template v-slot:filter-addData>
                <el-button :disabled="!canFlowEdit" @click="addData"
                  >添加配件</el-button
                >
              </template>
              <template v-slot:filter-removeData>
                <el-button :disabled="!canRemoveAsset" @click="removeData()"
                  >删除配件</el-button
                >
              </template>
            </PageFilter>
            <div class="flex_full_item">
              <el-form
                ref="partsTableForm"
                :model="tableInfoParts"
                style="width: 100%"
                :disabled="!canFlowEdit"
              >
                <!-- 表格 -->
                <PageTable
                  ref="tableInfoPartsTable"
                  :refresh="tableInfoParts.refresh"
                  :init-curpage="tableInfoParts.initCurpage"
                  v-model:data="tableInfoParts.data"
                  :api="tableInfoParts.api"
                  :query="tableInfoParts.query"
                  :checkBox="canFlowEdit"
                  :pager="false"
                  :tab-index="true"
                  :field-list="tableInfoParts.fieldList"
                  :handle="tableInfoParts.handle"
                  :isRowClickSelect="true"
                  :isDynamic="false"
                  @handleEvent="handleEventParts"
                >
                  <template v-slot:col-price="scope">
                    <el-form-item
                      :prop="`data.${scope.$index}.price`"
                      :rules="
                        scope.$index >= 0
                          ? [
                              {
                                validator: $validate.positiveMoneyNoZeroAsset,
                                trigger: ['blur', 'change'],
                              },
                              {
                                required: scope.$index >= 0,
                                message: '请输入单价',
                                trigger: 'blur',
                              },
                            ]
                          : []
                      "
                    >
                      <el-input-number
                        style="width: 100%; margintop: 18px"
                        v-model.lazy="scope.row.price"
                        clearable
                        controls-position="right"
                        :precision="
                          $store.state.permission.systemConfig
                            .assets_price_precision
                        "
                        @change="changePrice($event, scope.row, `price`)"
                        :min="0"
                        :max="99999999"
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-qty="scope">
                    <el-form-item
                      :prop="`data.${scope.$index}.qty`"
                      :rules="
                        scope.$index >= 0
                          ? [
                              {
                                validator: $validate.positiveNoAsset,
                                trigger: ['blur', 'change'],
                              },
                              {
                                required: scope.$index >= 0,
                                message: '请输入数量',
                                trigger: 'blur',
                              },
                            ]
                          : []
                      "
                    >
                      <el-input-number
                        style="width: 100%; margintop: 18px"
                        v-model.lazy="scope.row.qty"
                        clearable
                        controls-position="right"
                        :precision="2"
                        @change="changePrice($event, scope.row, `qty`)"
                        :min="1"
                        :max="999999"
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-useTime="scope">
                    <el-form-item
                      :prop="`data.${scope.$index}.useTime`"
                      :rules="
                        scope.$index >= 0
                          ? [
                              {
                                validator: validateUseTime,
                                trigger: 'blur',
                              },
                            ]
                          : []
                      "
                    >
                      <el-date-picker
                        v-model="scope.row.useTime"
                        type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="选择日期"
                      ></el-date-picker>
                    </el-form-item>
                  </template>
                </PageTable>
              </el-form>
            </div>
          </div>
        </div>
        <div class="model-panel model-panel-left">
          <div class="model-panel-title">
            <p>完工信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="finishInfoList"></basic-information>
          </div>
        </div>
        <div class="model-panel model-panel-left">
          <div class="model-panel-body">
            <div class="flex_full_item">
              <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane
                  class="model-panel-title"
                  label="处理记录"
                  name="first"
                >
                  <!-- 表格 -->
                  <el-form
                    v-if="activeName === 'first'"
                    ref="tableForm"
                    :model="dealInfo"
                    style="width: 100%"
                  >
                    <page-table
                      :refresh="dealInfo.refresh"
                      :init-curpage="dealInfo.initCurpage"
                      v-model:data="dealInfo.data"
                      :pager="false"
                      :check-box="false"
                      :tab-index="true"
                      :api="dealInfo.api"
                      :query="dealInfo.query"
                      :field-list="dealInfo.fieldList"
                      :handle="dealInfo.handle"
                      :isDynamic="false"
                      @handleEvent="handleEvent"
                    >
                      <template v-slot:col-filePathList="scope">
                        <UploadList
                          v-if="scope.row.filePathList"
                          :fileData="scope.row.filePathList"
                          :uploadDisabled="false"
                        />
                        <span v-else>-</span>
                      </template>
                    </page-table>
                  </el-form>
                </el-tab-pane>
                <el-tab-pane
                  class="model-panel-title"
                  label="派单记录"
                  name="second"
                >
                  <!-- 表格 -->
                  <el-form
                    v-if="activeName === 'second'"
                    ref="tableForm"
                    :model="dispatchTableInfo"
                    style="width: 100%"
                  >
                    <page-table
                      :refresh="dispatchTableInfo.refresh"
                      :init-curpage="dispatchTableInfo.initCurpage"
                      v-model:data="dispatchTableInfo.data"
                      :pager="false"
                      :check-box="false"
                      :tab-index="true"
                      :api="dispatchTableInfo.api"
                      :query="dispatchTableInfo.query"
                      :field-list="dispatchTableInfo.fieldList"
                      :handle="dispatchTableInfo.handle"
                      :isDynamic="false"
                      @handleEvent="handleEvent"
                    >
                    </page-table>
                  </el-form>
                </el-tab-pane>
                <el-tab-pane
                  class="model-panel-title"
                  label="维修记录"
                  name="third"
                >
                  <!-- 表格 -->
                  <el-form
                    v-if="activeName === 'third'"
                    ref="tableForm"
                    :model="maintenanceTableInfo"
                    style="width: 100%"
                  >
                    <page-table
                      :refresh="maintenanceTableInfo.refresh"
                      :init-curpage="maintenanceTableInfo.initCurpage"
                      v-model:data="maintenanceTableInfo.data"
                      :pager="false"
                      :check-box="false"
                      :tab-index="true"
                      :api="maintenanceTableInfo.api"
                      :query="maintenanceTableInfo.query"
                      :field-list="maintenanceTableInfo.fieldList"
                      :isDynamic="false"
                    >
                      <template v-slot:col-orderNo="scope">
                        <span
                          v-if="$permission('maintenanceOrder:view')"
                          class="slip-edit"
                          @click="showMaintenanceDetail(scope.row)"
                        >
                          {{ scope.row.orderNo || '-' }}
                        </span>
                        <span v-else>
                          {{ scope.row.orderNo || '-' }}
                        </span>
                      </template>
                    </page-table>
                  </el-form>
                </el-tab-pane>
                <el-tab-pane
                  class="model-panel-title"
                  label="配件使用"
                  name="fourth"
                >
                  <!-- 表格 -->
                  <page-table
                    v-if="activeName === 'fourth'"
                    :refresh="mountingsUseTableInfo.refresh"
                    :init-curpage="mountingsUseTableInfo.initCurpage"
                    v-model:data="mountingsUseTableInfo.data"
                    :pager="false"
                    :check-box="false"
                    :tab-index="true"
                    :api="mountingsUseTableInfo.api"
                    :query="mountingsUseTableInfo.query"
                    :field-list="mountingsUseTableInfo.fieldList"
                    :handle="mountingsUseTableInfo.handle"
                    :isDynamic="false"
                    @handleEvent="handleEvent"
                  />
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </div>

        <div class="model-panel model-panel-right">
          <div class="model-panel-body">
            <div class="flex_full_item">
              <el-tabs v-model="clickName" @tab-click="handleTabClick">
                <el-tab-pane
                  class="model-panel-title"
                  label="基本信息"
                  name="first"
                >
                  <basic-information :info="basicInfoList"></basic-information>
                </el-tab-pane>
                <el-tab-pane
                  class="model-panel-title"
                  label="验收信息"
                  name="second"
                >
                  <basic-information
                    :info="estimateInfoList"
                  ></basic-information>
                </el-tab-pane>
                <el-tab-pane
                  class="model-panel-title"
                  label="操作流水"
                  name="third"
                >
                  <Timeline :list="affairTableInfo.data" />
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </div>
        <chose-printer
          :visible="printerInfo.visible"
          @callBack="handlePrinterCallBack"
        />
      </FullScreen>
    </div>
    <!-- 派单/改派 -->
    <PageDialog
      v-show="sendOrderInfo.visible"
      :title="sendOrderInfo.title"
      v-model:visible="sendOrderInfo.visible"
      :width="sendOrderInfo.width"
      :bt-loading="sendOrderInfo.btLoading"
      :bt-list="sendOrderInfo.btList"
    >
      <PageForm
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="sendOrderInfo.formInfo.ref"
        :data="sendOrderInfo.formInfo.data"
        :field-list="sendOrderInfo.formInfo.fieldList"
        :rules="sendOrderInfo.formInfo.rules"
        :label-width="sendOrderInfo.formInfo.labelWidth"
      >
        <template v-slot:form-requireCompleteTime>
          <el-date-picker
            v-model="sendOrderInfo.formInfo.data.requireCompleteTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="productionTimePickerOptions.disabledDate"
            placeholder="选择日期"
          >
          </el-date-picker>
        </template>
        <template v-slot:form-acceptUserName>
          <el-input
            type="input"
            :disabled="true"
            class="not-mongolia"
            placeholder="请选择维修人员"
            v-model="sendOrderInfo.formInfo.data.acceptUserName"
          >
            <template #append>
              <el-icon @click="openRepairUserWindow"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
      </PageForm>
    </PageDialog>
    <!-- 维修人员 -->
    <SelectRepairUser
      v-if="selectRepairUserInfo.visible"
      v-model:showDialog="selectRepairUserInfo.visible"
      :api="selectRepairUserInfo.api"
      :checkedRowList="selectRepairUserInfo.checkedRowList"
      :check-box="true"
      :saveEmpty="true"
      :highlight-row="true"
      :query="selectRepairUserInfo.query"
      @callback="selectRepairUserCallBack"
    />
    <!-- 处理登记 -->
    <PageDialog
      v-show="registerInfo.visible"
      :title="registerInfo.title"
      v-model:visible="registerInfo.visible"
      :width="registerInfo.width"
      :bt-loading="registerInfo.btLoading"
      :bt-list="registerInfo.btList"
    >
      <PageForm
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="registerInfo.formInfo.ref"
        :data="registerInfo.formInfo.data"
        :field-list="registerInfo.formInfo.fieldList"
        :rules="registerInfo.formInfo.rules"
        :label-width="registerInfo.formInfo.labelWidth"
      >
        <template v-slot:form-startTime>
          <el-date-picker
            v-model="registerInfo.formInfo.data.startTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            :disabled-date="productionTimePickerOptions.disabledDate"
            placeholder="请选择开始时间"
          >
          </el-date-picker>
        </template>
        <template v-slot:form-endTime>
          <el-date-picker
            v-model="registerInfo.formInfo.data.endTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            :disabled-date="productionTimePickerOptions.disabledDate"
            placeholder="请选择结束时间"
          >
          </el-date-picker>
        </template>
        <template v-slot:form-filePathList>
          <el-upload
            :headers="registerInfo.uploadInfo.headers"
            :on-error="uploadError"
            :on-success="uploadAttachment"
            :on-remove="uploadRemove"
            :before-upload="beforeProductUpload"
            :on-exceed="handleExceed"
            :action="registerInfo.uploadInfo.action"
            :limit="registerInfo.uploadInfo.limit"
            :file-list="registerInfo.uploadInfo.fileList"
          >
            <el-button>点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                文件大小不超过{{
                  $store.state.permission.systemConfig.max_file_size
                }}M
              </div>
            </template>
          </el-upload>
        </template>
      </PageForm>
    </PageDialog>
    <!-- 完工 -->
    <PageDialog
      v-show="finishInfo.visible"
      :title="finishInfo.title"
      v-model:visible="finishInfo.visible"
      :width="finishInfo.width"
      :bt-loading="finishInfo.btLoading"
      :bt-list="finishInfo.btList"
    >
      <PageForm
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="finishInfo.formInfo.ref"
        :data="finishInfo.formInfo.data"
        :field-list="finishInfo.formInfo.fieldList"
        :rules="finishInfo.formInfo.rules"
        :label-width="finishInfo.formInfo.labelWidth"
      >
        <template v-slot:form-completeTime>
          <el-date-picker
            v-model="finishInfo.formInfo.data.completeTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            :shortcuts="productionTimePickerOptions"
            placeholder="选择完工时间"
          >
          </el-date-picker>
        </template>
      </PageForm>
    </PageDialog>
    <!-- 评价 -->
    <PageDialog
      v-show="estimateInfo.visible"
      :title="estimateInfo.title"
      v-model:visible="estimateInfo.visible"
      :width="estimateInfo.width"
      :bt-loading="estimateInfo.btLoading"
      :bt-list="estimateInfo.btList"
    >
      <Rate
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="estimateInfo.formInfo.ref"
        :data="estimateInfo.formInfo.data"
        :field-list="estimateInfo.formInfo.fieldList"
        :rules="estimateInfo.formInfo.rules"
        :label-width="estimateInfo.formInfo.labelWidth"
      >
      </Rate>
    </PageDialog>
    <!-- 详情页 -->
    <MaintenanceOrderDetail
      v-if="maintenanceOrderDetailInfo.visible"
      :id="maintenanceOrderDetailInfo.id"
      v-model:visible="maintenanceOrderDetailInfo.visible"
      :title="maintenanceOrderDetailInfo.title"
      @returnBack="getDetails"
    />
    <!-- 院外报修 -->
    <PageDialog
      v-show="outsideRepairInfo.visible"
      :title="outsideRepairInfo.title"
      v-model:visible="outsideRepairInfo.visible"
      :width="outsideRepairInfo.width"
      :bt-loading="outsideRepairInfo.btLoading"
      :bt-list="outsideRepairInfo.btList"
    >
      <PageForm
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="outsideRepairInfo.formInfo.ref"
        :data="outsideRepairInfo.formInfo.data"
        :field-list="outsideRepairInfo.formInfo.fieldList"
        :rules="outsideRepairInfo.formInfo.rules"
        :label-width="outsideRepairInfo.formInfo.labelWidth"
      >
        <template v-slot:form-requireCompleteTime>
          <el-date-picker
            v-model="outsideRepairInfo.formInfo.data.requireCompleteTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            :picker-options="productionTimePickerOptions"
            placeholder="选择日期"
          >
          </el-date-picker>
        </template>
        <template v-slot:form-maintenanceName>
          <el-input
            type="input"
            :disabled="true"
            :class="disabledMaintenanceName ? '' : 'not-mongolia'"
            placeholder="请选择维保商"
            v-model="outsideRepairInfo.formInfo.data.maintenanceName"
          >
            <template #append>
              <el-icon @click="openMaintenanceProviderWindow"
                ><MoreFilled
              /></el-icon>
            </template>
          </el-input>
        </template>
        <template v-slot:form-maintenanceUserName>
          <el-input
            v-model="outsideRepairInfo.formInfo.data.maintenanceUserName"
            type="input"
            :disabled="true"
            class="not-mongolia"
            placeholder="请选择维保联系人"
          >
            <template #append>
              <el-icon @click="openMaintenanceContactsList"
                ><MoreFilled
              /></el-icon>
            </template>
          </el-input>
        </template>
      </PageForm>
    </PageDialog>
    <!-- 维保商 -->
    <SelectMaintenance
      v-if="selectMaintenanceProvider.visible"
      v-model:show-dialog="selectMaintenanceProvider.visible"
      :query="selectMaintenanceProvider.query"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      @callback="selectMaintenanceProviderCallback"
    />
    <!-- 维保联系人 -->
    <SelectRepairUser
      v-if="selectMaintenanceContactsInfo.visible"
      v-model:showDialog="selectMaintenanceContactsInfo.visible"
      :api="selectMaintenanceContactsInfo.api"
      :saveEmpty="true"
      :query="selectMaintenanceContactsInfo.query"
      :check-box="false"
      :highlight-row="true"
      :showPermission="false"
      @callback="selectMaintenanceContactsCallBack"
    />
    <!-- 选择配件 -->
    <SelectAccessories
      v-if="selectPartsObj.visible"
      v-model:show-dialog="selectPartsObj.visible"
      :query="selectPartsObj.query"
      :tableKey="selectPartsObj.tableKey"
      @callback="callBackAccessories"
    />
    <Modify
      v-if="modifyInfo.visible"
      :id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="modifyCallback"
    />
  </div>
</template>

<script setup name="repairRepairManageRepairOrderDetails">
import UploadVideo from '@/components/UploadVideo/index'
import UploadList from '@/components/UploadVideo/uploadList'
import { selectByCodeAndDept } from '@/api/report.js'
import { doPrint } from '@/utils/exportUtil.js'
import {
  getSelectUserWithPermission,
  getMaintenanceGroupsUserPage,
  transferRepairOrder,
  updateDispatchRepairOrder,
  getRepairPartsAffairAll,
  reminderRepairOrder,
  getMaintenceOrderAll,
  getRepairOrderById,
  getRepairDealAffairAll,
  repairDealAffair,
  confirmRepairOrder,
  cannelRepairOrder,
  completeDealRepairOrder,
  dispatchRepairOrder,
  revokeRepairOrder,
  getRepairDispatchAffairAll,
  getDispatchUserAll,
  submitRepairOrder,
  approvedRepairOrder,
  rejectRepairOrder,
  refuseRepairOrder,
  recallRepairOrder,
  cancelCheckRepairOrder,
  getRepairPartsAffairPage,
} from '@/api/repair'
import { getAssetById } from '@/api/core'
import {
  assetCodePrint,
  getAssetCardPrint,
  exportAssetCardDetail,
} from '@/api/core'
import { orderOpAffairAll } from '@/api/affair'
import { fatchTemplateByCode } from '@/api/base'
import SelectRepairUser from '@/components/SelectUsers/selectMaintenanceUsers'
import axios from 'axios'
import moment from 'moment'
import { ElLoading, ElMessage } from 'element-plus'
import MaintenanceOrderDetail from '@/views/repair/repairManage/maintenanceOrder/details.vue'
import { getTripartiteSystemProject } from '@/api/cmPreMgt'
const SelectProject = defineAsyncComponent(() => import('./selectProject'))
const Modify = defineAsyncComponent(() => import('./modify'))
const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps(['visible', 'id', 'flowFormType', 'noOrderType'])

let validateTime = (rule, value, callback) => {
  let currentTime = moment(new Date()).format('YYYY-MM-DD')
  let requireTime = moment(value).format('YYYY-MM-DD')
  if (requireTime < currentTime) {
    callback(new Error('要求完成时间不能小于当前日期！'))
  } else {
    callback()
  }
}
let validateCompleteTime = (rule, value, callback) => {
  let currentTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
  if (value > currentTime) {
    callback(new Error('完工时间不能大于当前时间！'))
  } else {
    callback()
  }
}

let validateStartTime = (rule, value, callback) => {
  let endTime = registerInfo.formInfo.data.endTime
  if (endTime) {
    if (endTime < value) {
      callback(new Error('开始时间不能大于结束时间！'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
let validateEndTime = (rule, value, callback) => {
  let startTime = registerInfo.formInfo.data.startTime
  if (startTime) {
    if (startTime > value) {
      callback(new Error('结束时间不能小于开始时间！'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

const activeName = ref('first')
const clickName = ref('first')
const title = ref('报修单详情')
const btnList = ref([])
const productionTimePickerOptions = ref({})
const isDispatchUser = ref(false)
//报修信息
const infoList = ref({})
const printerInfo = reactive({
  visible: false,
  data: {},
})
//明细相关
const maintenanceOrderDetailInfo = reactive({
  visible: false,
  title: '维修单详情',
  id: '',
})
//基础信息
const baseInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '报修单号',
      value: 'orderNo',
      type: 'text',
    },
    {
      label: '报修人',
      value: 'repairUserName',
      type: 'text',
    },
    {
      label: '报修人电话',
      value: 'repairUserTel',
      type: 'text',
    },
    {
      label: '报修部门',
      value: 'repairDeptName',
      type: 'text',
    },
    {
      label: '报修时间',
      value: 'createTime',
      type: 'text',
    },
    {
      label: '状态',
      value: 'statusValue',
      type: 'text',
    },
    {
      label: '维修渠道',
      value: 'maintainChannelName',
      type: 'text',
    },
    {
      label: '院区',
      value: 'hospitalAreaValue',
      type: 'text',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'popover',
    },
  ],
})

const repairInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '报修类型',
      value: 'repairTypeName',
      type: 'text',
    },
    {
      label: '资产',
      value: 'assetName',
      type: 'text',
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'text',
    },
    {
      label: '资产分类',
      value: 'classifyTypeValue',
      type: 'text',
    },
    {
      label: '使用部门',
      value: 'useDeptName',
      type: 'text',
      show: true,
    },
    {
      label: '仓库',
      value: 'depotName',
      type: 'text',
      show: false,
    },
    {
      label: '维修类别',
      value: 'notAssetRepairTypeValue',
      type: 'text',
      show: false,
    },
    {
      label: '资产位置',
      value: 'location',
      type: 'text',
    },
    {
      label: '紧急程度',
      value: 'urgencyDegreeName',
      type: 'text',
    },
    {
      label: '是否停机',
      value: 'isHaltName',
      type: 'text',
    },
    {
      label: '是否医疗设备',
      value: 'isMedicalEquipmentValue',
      type: 'text',
    },
    {
      label: '故障部位',
      value: 'faultPart',
      type: 'text',
    },
    {
      label: '故障发生时间',
      value: 'faultTime',
      type: 'text',
    },
    {
      label: '期望完成时间',
      value: 'expectCompleteTime',
      type: 'text',
    },
    {
      label: '维保商',
      value: 'maintenanceName',
      type: 'text',
    },

    {
      label: '维保联系人',
      value: 'maintenanceUserName',
      type: 'text',
    },
    {
      label: '维保联系人电话',
      value: 'maintenanceUserTel',
      type: 'text',
    },
    {
      label: '实际维修人',
      value: 'actualMaintenanceUserName',
      type: 'text',
    },
    {
      label: '故障描述',
      value: 'faultDescribe',
      type: 'popover',
    },
    {
      label: '故障图片/语音',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
  ],
})
const noMaintenanceNameInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '报修类型',
      value: 'repairTypeName',
      type: 'text',
    },

    {
      label: '资产',
      value: 'assetName',
      type: 'text',
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'text',
    },
    {
      label: '使用部门',
      value: 'useDeptName',
      type: 'text',
      show: true,
    },
    {
      label: '仓库',
      value: 'depotName',
      type: 'text',
      show: false,
    },
    {
      label: '维修类别',
      value: 'notAssetRepairTypeValue',
      type: 'text',
      show: false,
    },
    {
      label: '资产位置',
      value: 'location',
      type: 'text',
    },
    {
      label: '资产分类',
      value: 'classifyTypeValue',
      type: 'text',
    },

    {
      label: '紧急程度',
      value: 'urgencyDegreeName',
      type: 'text',
    },
    {
      label: '是否停机',
      value: 'isHaltName',
      type: 'text',
    },
    {
      label: '是否医疗设备',
      value: 'isMedicalEquipmentValue',
      type: 'text',
    },
    {
      label: '故障部位',
      value: 'faultPart',
      type: 'text',
    },
    {
      label: '故障发生时间',
      value: 'faultTime',
      type: 'text',
    },
    {
      label: '期望完成时间',
      value: 'expectCompleteTime',
      type: 'text',
    },
    // {
    //   label: "维保商",
    //   value: "maintenanceName",
    //   type: "text",
    // },
    {
      label: '维保联系人',
      value: 'maintenanceUserName',
      type: 'text',
    },
    {
      label: '维保联系人电话',
      value: 'maintenanceUserTel',
      type: 'text',
    },
    {
      label: '实际维修人',
      value: 'actualMaintenanceUserName',
      type: 'text',
    },
    {
      label: '故障描述',
      value: 'faultDescribe',
      type: 'popover',
    },
    {
      label: '故障图片/语音',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
  ],
})
//完工信息
const finishInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '处理工时(h)',
      value: 'dealTime',
      type: 'text',
    },
    {
      label: '维修材料费(元)',
      value: 'materialAmount',
      type: 'text',
    },
    {
      label: '维修服务费(元)',
      value: 'serviceAmount',
      type: 'text',
    },
  ],
})
//鉴定意见信息-详情
const repairPriceInfoList = ref({
  data: {
    estimateAmount: 0,
    repairPartsPrice: 0,
    appraisalContent: '',
  },
  fieldList: [
    {
      label: '维修服务费',
      value: 'estimateAmount',
      type: 'text',
    },
    {
      label: '维修配件费用',
      value: 'repairPartsPrice',
      type: 'text',
    },
    {
      label: '鉴定内容',
      value: 'appraisalContent',
      type: 'text',
    },
  ],
})
//鉴定意见信息-可编辑
const repairPriceSlotInfoList = ref({
  ref: '',
  data: {
    estimateAmount: '',
    repairPartsPrice: '',
    appraisalContent: '',
  },
  fieldList: [
    {
      label: '维修服务费',
      value: 'estimateAmount',
      type: 'slot',
      required: true,
    },
    {
      label: '维修配件费用',
      value: 'repairPartsPrice',
      type: 'text',
    },
    {
      label: '鉴定内容',
      value: 'appraisalContent',
      type: 'slot',
    },
  ],
  rules: {
    estimateAmount: [
      { required: true, message: '请输入维修服务费', trigger: 'blur' },
    ],
  },
})
//基础信息
const basicInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '报修单号',
      value: 'orderNo',
      type: 'text',
    },
    {
      label: '状态',
      value: 'statusValue',
      type: 'text',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'popover',
    },
    {
      label: '创建人',
      value: 'createUserName',
      type: 'text',
    },
    {
      label: '创建时间',
      value: 'createTime',
      type: 'text',
    },
    {
      label: '最后更新人',
      value: 'updateUserName',
      type: 'text',
    },
    {
      label: '最后更新时间',
      value: 'updateTime',
      type: 'text',
    },
  ],
})
//评价信息
const estimateInfoList = reactive({
  data: [],
  fieldList: [
    {
      label: '是否已修复',
      value: 'isRepairName',
      type: 'text',
    },
    {
      label: '综合评分',
      value: 'compositeScore',
      type: 'text',
    },
    {
      label: '服务态度',
      value: 'serviceAttitude',
      type: 'text',
    },
    {
      label: '响应速度',
      value: 'responseSpeed',
      type: 'text',
    },
    {
      label: '技术水平',
      value: 'skillLevel',
      type: 'text',
    },
    {
      label: '建议评价',
      value: 'suggest',
      type: 'popover',
    },
  ],
})
// 处理记录
const dealInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: getRepairDealAffairAll,
  data: [],
  query: {
    orderType: props.flowFormType || props.noOrderType ? null : 53,
    orderId: props.id,
    sort: 'create_time desc',
  },
  fieldList: [
    { label: '处理人', value: 'dealUserName' },
    { label: '开始时间', value: 'startTime' },
    { label: '结束时间', value: 'endTime' },
    { label: '处理进度(%)', value: 'dealRate' },
    { label: '工作说明', value: 'dealDescribe' },
    { label: '附件', value: 'filePathList', type: 'slot', width: 200 },
  ],
})
// 派单记录
const dispatchTableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: getRepairDispatchAffairAll,
  data: [],
  query: {
    orderId: props.id,
    sort: 'create_time desc',
  },
  fieldList: [
    { label: '维修单号', value: 'dispatchNo' },
    { label: '派单方式', value: 'dispatchTypeName' },
    { label: '派单人', value: 'dispatchUserName' },
    { label: '维修人', value: 'acceptUserName' },
    { label: '派单时间', value: 'createTime' },
    { label: '派单说明', value: 'dispatchDescribe' },
  ],
})
// 配件预估表单
const tableInfoParts = ref({
  api: getRepairPartsAffairPage,
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  query: {
    maintenanceId: '',
    sort: 'create_time desc',
  },
  fieldList: [
    {
      label: '配件名称',
      value: 'commonName',
      width: '140px',
    },
    {
      label: '单价',
      value: 'price',
      type: 'slot',
    },
    {
      label: '数量',
      value: 'qty',
      type: 'slot',
    },
    {
      label: '金额',
      value: 'sumAmount',
      max: 999999999999999,
      formatter: proxy.$fn.TripartiteMethodAsset,
      width: '100px',
    },
    // {
    //   label: '更换日期',
    //   value: 'useTime',
    //   type: 'slot',
    // },
    {
      label: '计量单位',
      value: 'unitName',
      width: '80px',
    },
    {
      label: '规格',
      value: 'standard',
      width: '80px',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeData,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: props.flowFormType === 'engineer',
      },
    ],
  },
})
// 维修记录
const maintenanceTableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: getMaintenceOrderAll,
  data: [],
  query: {
    repairId: props.id,
    // orderId: props.id,
    sort: 'create_time desc',
  },
  fieldList: [
    { label: '维修单号', value: 'orderNo', type: 'slot' },
    { label: '状态', value: 'statusValue' },
    { label: '维修人', value: 'maintenanceUserName' },
    { label: '维修人电话', value: 'maintenanceUserTel' },
  ],
})
// 配件使用记录
const mountingsUseTableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: getRepairPartsAffairAll,
  data: [],
  query: {
    repairId: props.id,
    sort: 'create_time desc',
  },
  fieldList: [
    { label: '使用配件', value: 'commonName' },
    { label: '规格', value: 'standard' },
    { label: '计量单位', value: 'unitName' },
    { label: '单价', value: 'price' },
    { label: '数量', value: 'qty' },
    { label: '金额', value: 'sumAmount' },
    { label: '更换日期', value: 'useTime' },
    // { label: "备注", value: "remark" },
  ],
})
// 操作流水
const affairTableInfo = reactive({
  data: [],
  query: {
    orderType: 53,
    orderId: props.id,
    sort: 'operate_time desc',
  },
})
// 过滤相关配置
const customFilterInfo = reactive({
  query: {
    queryMap: {
      id: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {
      // isAssetAchievesExcel: "true",
    },
  },
})
//派单、改派相关
const sendOrderInfo = reactive({
  visible: false,
  title: '',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseSendOrder, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveSendOrder,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '要求完成时间',
        value: 'requireCompleteTime',
        type: 'slot',
        // required: true,
      },
      {
        label: '派单给',
        value: 'acceptUserName',
        type: 'slot',
        required: true,
      },
      {
        label: '派单说明',
        value: 'dispatchDescribe',
        type: 'textarea',
      },
    ],
    rules: {
      requireCompleteTime: [
        // {
        //   required: true,
        //   message: '请选择要求完成时间',
        //   trigger: 'change',
        // },
        {
          validator: validateTime,
          trigger: 'blur',
        },
      ],
      acceptUserName: [
        {
          required: true,
          message: '请选择维修人员',
          trigger: 'change',
        },
      ],
    },
    labelWidth: '120px',
  },
})
//处理登记相关
const registerInfo = reactive({
  visible: false,
  title: '处理登记',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseRegister, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveRegister,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '处理人',
        value: 'dealUserName',
        type: 'input',
        disabled: true,
      },

      {
        label: '开始时间',
        value: 'startTime',
        type: 'slot',
        required: true,
      },
      {
        label: '结束时间',
        value: 'endTime',
        type: 'slot',
        required: true,
      },
      {
        label: '处理进度(%)',
        value: 'dealRate',
        type: 'number',
        precision: 2,
        max: 100,
        // required: true,
      },
      {
        label: '工作说明',
        value: 'dealDescribe',
        type: 'textarea',
        required: true,
      },
      {
        label: '附件',
        value: 'filePathList',
        type: 'slot',
        className: 'not-br',
      },
    ],
    rules: {
      startTime: [
        {
          required: true,
          message: '请选择开始时间',
          trigger: 'change',
        },
        {
          validator: validateStartTime,
          trigger: 'blur',
        },
      ],
      endTime: [
        {
          required: true,
          message: '请选择结束时间',
          trigger: 'change',
        },
        {
          validator: validateEndTime,
          trigger: 'blur',
        },
      ],
      dealDescribe: [
        {
          required: true,
          message: '请输入工作说明',
          trigger: 'blur',
        },
      ],
    },
    labelWidth: '110px',
  },
  uploadInfo: {
    action: axios.defaults.baseURL + '/pub/uploadfile',
    headers: {
      Authorization: proxy.$store.state.user.token,
    },
    loading: {},
    limit: 3,
    fileList: [],
    fileSize: proxy.$store.state.permission.systemConfig.max_file_size,
    fileType: [
      'png',
      'jpg',
      'jpeg',
      'pdf',
      'gif',
      'mp3',
      'm4a',
      'aac',
      'wav',
      'audio',
      'x-m4a',
      'doc',
      'docx',
      'xls',
      'xlsx',
    ],
  },
})
//完工相关
const finishInfo = reactive({
  visible: false,
  title: '完工',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseFinish, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveFinish,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '完工时间',
        value: 'completeTime',
        type: 'slot',
        required: true,
      },
      {
        label: '完工说明',
        value: 'completeDescribe',
        type: 'textarea',
        required: true,
      },
    ],
    rules: {
      completeTime: [
        {
          required: true,
          message: '请选择完工时间',
          trigger: 'change',
        },
        {
          validator: validateCompleteTime,
          trigger: 'blur',
        },
      ],
      completeDescribe: [
        {
          required: true,
          message: '请输入完工说明',
          trigger: 'blur',
        },
      ],
    },
    labelWidth: '100px',
  },
})
//院外报修
const outsideRepairInfo = reactive({
  visible: false,
  title: '院外报修',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseOutsideRepair, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveOutsideRepair,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '资产',
        value: 'assetName',
        type: 'input',
        required: true,
        disabled: false,
      },
      {
        label: '要求完成时间',
        value: 'requireCompleteTime',
        type: 'slot',
        // required: true,
      },
      {
        label: '维保商',
        value: 'maintenanceName',
        type: 'slot',
        required: true,
      },
      {
        label: '维保商联系人',
        value: 'maintenanceUserName',
        type: 'slot',
      },
      {
        label: '维保商联系人电话',
        value: 'maintenanceUserTel',
        type: 'input',
      },
    ],
    rules: {
      assetName: [
        {
          required: true,
          message: '请输入资产',
          trigger: 'blur',
        },
      ],
      requireCompleteTime: [
        // {
        //   required: true,
        //   message: '请选择要求完成时间',
        //   trigger: 'change',
        // },
        {
          validator: validateTime,
          trigger: 'blur',
        },
      ],
      maintenanceName: [
        {
          required: true,
          message: '请选择维保商',
          trigger: 'change',
        },
      ],
      maintenanceUserTel: [
        {
          validator: proxy.$validate.cellphone,
          trigger: 'blur',
        },
      ],
    },
    labelWidth: '150px',
  },
})
//评价相关
const estimateInfo = reactive({
  visible: false,
  title: '评价',
  btLoading: false,
  type: '',
  msg: '',
  width: '30%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseEstimate, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveEstimate,
      show: true,
      disabled: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '是否已修复',
        value: 'isRepair',
        type: 'radio-model',
        code: 'yes_or_no',
        className: 'isReprir',
      },
      {
        label: '综合评分',
        value: 'compositeScore',
        type: 'showText',
        texts: ['1.0', '2.0', '3.0', '4.0', '5.0'],
      },
      {
        label: '服务态度',
        value: 'serviceAttitude',
        type: 'showText',
        texts: ['1.0', '2.0', '3.0', '4.0', '5.0'],
      },
      {
        label: '响应速度',
        value: 'responseSpeed',
        type: 'showText',
        texts: ['1.0', '2.0', '3.0', '4.0', '5.0'],
      },
      {
        label: '技术水平',
        value: 'skillLevel',
        type: 'showText',
        texts: ['1.0', '2.0', '3.0', '4.0', '5.0'],
      },
      {
        label: '建议评价',
        value: 'suggest',
        type: 'textarea',
        placeholder: '为了更好的为您服务，请留下您宝贵的意见',
      },
    ],
    rules: {},
    labelWidth: '120px',
  },
})
//选择维修人员
const selectRepairUserInfo = reactive({
  visible: false,
  saveEmpty: true,
  api: getSelectUserWithPermission,
  query: {
    orgId: '',
    assetId: '',
    deptId: '',
    depotId: '',
    assetClassifyId: '',
    notAssetRepairType: '',
  },
})
const selectMaintenanceContactsInfo = reactive({
  visible: false,
  saveEmpty: true,
  api: getSelectUserWithPermission,
  query: {
    orgId: '',
    assetId: '',
    deptId: '',
    depotId: '',
    assetClassifyId: '',
    notAssetRepairType: '',
  },
})
const selectMaintenanceProvider = reactive({
  visible: false,
  query: {
    orgId: '',
  },
})
const disabledMaintenanceName = ref(false)
const selectPartsObj = ref({
  visible: false,
  tableKey:
    'accessoriesArchivesDialog-com.slip.spd.entity.vo.asset.settings.AccessoriesArchivesVO',
  query: {
    id: {
      queryType: 'NOT_IN',
      queryCategory: 'AND',
      value: '',
    },
  },
})
// 过滤相关配置
const filterInfo = ref({
  query: {},
  list: [
    { type: 'slot', value: 'addData' },
    { type: 'slot', value: 'removeData' },
  ],
})
// 报修单编辑
const modifyInfo = ref({
  visible: false,
  title: '修改报修单',
  id: '',
})
const popoverVisible = ref(false)
const templateArr = ref([])

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canPrint = computed(() => {
  return (
    proxy.$permission('repairOrder:print') && baseInfoList.data.status !== 8
  )
})
const canExcel = computed(() => {
  return (
    proxy.$permission('repairOrder:excel') && baseInfoList.data.status !== 1
  )
})
const canReminder = computed(() => {
  return (
    proxy.$permission('repairOrder:reminder') &&
    (baseInfoList.data.status === 2 ||
      baseInfoList.data.status === 1 ||
      baseInfoList.data.status === 3) &&
    baseInfoList.data.maintainChannel !== 1
  )
})
const canRevoke = computed(() => {
  return (
    proxy.$permission('repairOrder:revoke') &&
    (baseInfoList.data.status === 2 || baseInfoList.data.status === 1) &&
    (baseInfoList.data.repairUser ===
      proxy.$store.state.user.userInfo.user.id ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
})
const canSendOrder = computed(() => {
  return (
    proxy.$permission('repairOrder:sendOrder') &&
    baseInfoList.data.status === 1 &&
    baseInfoList.data.maintainChannel !== 1 &&
    (isDispatchUser.value ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
})
const canUpdateSendOrder = computed(() => {
  return (
    proxy.$permission('repairOrder:updateSendOrder') &&
    (baseInfoList.data.status === 2 || baseInfoList.data.status === 5) &&
    baseInfoList.data.maintainChannel !== 1 &&
    (isDispatchUser.value ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
})
const canPrintAsset = computed(() => {
  return (
    proxy.$permission('repairOrder:printAsset') &&
    baseInfoList.data.status !== 1 &&
    baseInfoList.data.status !== 2
  )
})
const canEstimate = computed(() => {
  return (
    proxy.$permission('repairOrder:estimate') &&
    baseInfoList.data.status === 4 &&
    (proxy.$store.state.user.userInfo.user.type !== 'normal' ||
      proxy.$store.state.permission.systemConfig
        .repair_evaluation_only_oneself == 0 ||
      (proxy.$store.state.permission.systemConfig
        .repair_evaluation_only_oneself == 1 &&
        baseInfoList.data.repairUser ===
          proxy.$store.state.user.userInfo.user.id))
  )
})
const canHandleRegister = computed(() => {
  return (
    proxy.$permission('repairOrder:handleRegister') &&
    (baseInfoList.data.status === 1 || baseInfoList.data.status === 2) &&
    baseInfoList.data.maintainChannel !== 1 &&
    (isDispatchUser.value ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
})
const canFinish = computed(() => {
  return (
    proxy.$permission('repairOrder:finish') &&
    (baseInfoList.data.status === 1 || baseInfoList.data.status === 2) &&
    baseInfoList.data.maintainChannel !== 1 &&
    (isDispatchUser.value ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
})
const canTransfer = computed(() => {
  return (
    proxy.$permission('repairOrder:transfer') &&
    (baseInfoList.data.status === 1 ||
      baseInfoList.data.status === 2 ||
      baseInfoList.data.status === 5) &&
    baseInfoList.data.maintainChannel !== 1 &&
    (isDispatchUser.value ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
})
const canCancelFinish = computed(() => {
  return (
    proxy.$permission('repairOrder:cancelFinish') &&
    baseInfoList.data.status === 4 &&
    baseInfoList.data.maintainChannel !== 1 &&
    baseInfoList.data.repairUser === proxy.$store.state.user.userInfo.user.id &&
    (isDispatchUser.value ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
})
const canEdit = computed(() => {
  return (
    proxy.$permission('repairOrder:update') &&
    (baseInfoList.data.status === 8 || baseInfoList.data.status === 12) &&
    (baseInfoList.data.repairUser ===
      proxy.$store.state.user.userInfo.user.id ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
})
// 撤回
const canRecall = computed(() => {
  return (
    ((proxy.$permission('repairOrder:recall') &&
      baseInfoList.data.status === 9) ||
      (proxy.$store.state.permission.systemConfig.allow_repair_approval == 0 &&
        baseInfoList.data.status === 1)) &&
    baseInfoList.data.source != 1
  )
})
// 批准
const canAccept = computed(() => {
  return (
    proxy.$permission('repairOrder:approve') &&
    proxy.$store.state.permission.systemConfig.allow_repair_approval == 1 &&
    baseInfoList.data.status === 9
  )
})
// 驳回
const canReject = computed(() => {
  return (
    proxy.$permission('repairOrder:reject') &&
    proxy.$store.state.permission.systemConfig.allow_repair_approval == 1 &&
    baseInfoList.data.status === 9
  )
})
// 拒绝
const canRefuse = computed(() => {
  return (
    proxy.$permission('repairOrder:refuse') &&
    proxy.$store.state.permission.systemConfig.allow_repair_approval == 1 &&
    baseInfoList.data.status === 9
  )
})
// 销审
const canSalesReview = computed(() => {
  return (
    proxy.$permission('repairOrder:salesReview') &&
    proxy.$store.state.permission.systemConfig.allow_repair_approval !== 0 &&
    baseInfoList.data.status === 1 &&
    baseInfoList.data.source != 1
  )
})
const canSubmit = computed(() => {
  return (
    proxy.$permission('repairOrder:submit') &&
    (baseInfoList.data.status === 8 || baseInfoList.data.status === 12) &&
    (baseInfoList.data.repairUser ===
      proxy.$store.state.user.userInfo.user.id ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
})
const canRemoveAsset = computed(() => {
  return tableInfoParts.value.selections.length
})
const canFlowEdit = computed(() => {
  return props.flowFormType === 'engineer'
})

watch(
  () => props.visible,
  (newVal) => {
    showDialog.value = newVal
  },
  {
    immediate: true,
  }
)
watch(
  () => props.id,
  (newVal) => {
    maintenanceTableInfo.query.repairId = newVal
    dealInfo.query.orderId = newVal
    dispatchTableInfo.query.orderId = newVal
    affairTableInfo.query.orderId = newVal
    customFilterInfo.query.queryMap.id.value = newVal
    mountingsUseTableInfo.query.repairId = newVal
    getDetails()
  },
  {
    immediate: true,
    deep: true,
  }
)
watch(
  () => estimateInfo.formInfo.data,
  (val) => {
    if (val) {
      if (
        (val.isRepair == 1 || val.isRepair == 0) &&
        val.compositeScore &&
        val.serviceAttitude &&
        val.responseSpeed &&
        val.skillLevel
      ) {
        estimateInfo.btList[1].disabled = false
      } else {
        estimateInfo.btList[1].disabled = true
      }
    } else {
      estimateInfo.btList[1].disabled = true
    }
  },
  {
    deep: true,
  }
)
watch(
  () => baseInfoList.data,
  (val) => {
    if (val) {
      if (val.maintainChannel === 1) {
        //维保商显示
        infoList.value = repairInfoList
      } else if (val.maintainChannel === 2) {
        //维保商隐藏
        infoList.value = noMaintenanceNameInfoList
      }
    }
  },
  {
    deep: true,
  }
)
// 计算维修配件费用
watch(
  () => tableInfoParts.value.data,
  (val) => {
    let sumPrice = 0
    val.forEach((item) => {
      if (item.sumAmount) {
        sumPrice += item.sumAmount
      }
    })
    repairPriceSlotInfoList.value.data['repairPartsPrice'] = sumPrice
  },
  {
    immediate: true,
    deep: true,
  }
)

onMounted(() => {
  getDispatchUser()
})

function getFlowFormInfo() {
  tableInfoParts.value.data.forEach((item) => {
    item.repairId = props.id
    item.calcQty = item.qty
  })
  const totalAmount =
    (repairPriceSlotInfoList.value.data.repairPartsPrice || 0) +
    (repairPriceSlotInfoList.value.data.estimateAmount || 0)
  const info = {
    id: props.id,
    estimateAmount: repairPriceSlotInfoList.value.data.estimateAmount,
    totalAmount: totalAmount,
    repairPartsEstimateList: tableInfoParts.value.data,
    appraisalContent: repairPriceSlotInfoList.value.data.appraisalContent,
  }
  // 非维修工程师外其它表单什么都不传
  if (props.flowFormType !== 'engineer') {
    return null
  }
  return info
}
async function submitForm() {
  // 非维修工程师外其它表单不做校验
  if (props.flowFormType !== 'engineer') {
    return true
  }
  let tempBoolForm = false
  let tempBoolTable = false
  await repairPriceSlotInfoList.value.ref.validate((valid) => {
    if (valid) {
      tempBoolForm = true
    } else {
      tempBoolForm = false
      return false
    }
  })
  await proxy.$refs['partsTableForm'].validate((valid) => {
    if (valid) {
      tempBoolTable = true
    } else {
      tempBoolTable = false
      return false
    }
  })
  return tempBoolForm && tempBoolTable
}
//维保商
function openMaintenanceProviderWindow() {
  if (!disabledMaintenanceName.value) {
    selectMaintenanceProvider.visible = true
  }
}

//维保联系人
function openMaintenanceContactsList() {
  if (outsideRepairInfo.formInfo.data.maintainChannel == 1) {
    if (!outsideRepairInfo.formInfo.data.maintenanceName) {
      proxy.$message({
        type: 'warning',
        duration: 3500,
        message: '请先选择维保商',
        showClose: true,
      })
      return
    }
  }
  selectMaintenanceContactsInfo.query.orgId =
    outsideRepairInfo.formInfo.data.maintenanceId === -2
      ? ''
      : outsideRepairInfo.formInfo.data.maintenanceId

  selectMaintenanceContactsInfo.query.assetId =
    baseInfoList.data.assetId === -2 ? '' : baseInfoList.data.assetId
  selectMaintenanceContactsInfo.query.deptId =
    baseInfoList.data.useDeptId === -2 ? '' : baseInfoList.data.useDeptId
  selectMaintenanceContactsInfo.query.depotId =
    baseInfoList.data.depotId === -2 ? '' : baseInfoList.data.depotId
  selectMaintenanceContactsInfo.query.assetClassifyId =
    baseInfoList.data.classifyType === -2 ? '' : baseInfoList.data.classifyType
  selectMaintenanceContactsInfo.query.notAssetRepairType =
    baseInfoList.data.notAssetRepairType === -2
      ? ''
      : baseInfoList.data.notAssetRepairType
  selectMaintenanceContactsInfo.visible = true
}
//维保商
function selectMaintenanceProviderCallback(row) {
  if (row) {
    outsideRepairInfo.formInfo.data.maintenanceName = row.maintenanceName
    outsideRepairInfo.formInfo.data.maintenanceId = row.maintenanceId
    outsideRepairInfo.formInfo.data.maintenanceUser = ''
    outsideRepairInfo.formInfo.data.maintenanceUserName = ''
  } else {
    outsideRepairInfo.formInfo.data.maintenanceName = ''
    outsideRepairInfo.formInfo.data.maintenanceId = ''
    outsideRepairInfo.formInfo.data.maintenanceUser = ''
    outsideRepairInfo.formInfo.data.maintenanceUserName = ''
  }
}
//维保联系人
function selectMaintenanceContactsCallBack(row) {
  if (row) {
    outsideRepairInfo.formInfo.data.maintenanceUser = row.userId
    outsideRepairInfo.formInfo.data.maintenanceUserName = row.name
    outsideRepairInfo.formInfo.data.maintenanceUserTel = row.tel
  } else {
    outsideRepairInfo.formInfo.data.maintenanceUser = -2
    outsideRepairInfo.formInfo.data.maintenanceUserName = ''
    outsideRepairInfo.formInfo.data.maintenanceUserTel = ''
  }
}
function handleCloseOutsideRepair() {
  outsideRepairInfo.visible = false
  outsideRepairInfo.formInfo.data = {}
}
function saveOutsideRepair() {
  outsideRepairInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      transferRepairOrder(outsideRepairInfo.formInfo.data).then((resp) => {
        if (resp && resp.success) {
          getDetails()
        }
        outsideRepairInfo.formInfo.data = {}
        outsideRepairInfo.visible = false
      })
    }
  })
}
function transfer() {
  let row = baseInfoList.data
  //院外报修

  if (row.assetId > 0) {
    outsideRepairInfo.formInfo.fieldList.forEach((item) => {
      if (item.value === 'assetName') {
        item.disabled = true
      }
    })
  } else {
    outsideRepairInfo.formInfo.fieldList.forEach((item) => {
      if (item.value === 'assetName') {
        item.disabled = false
      }
    })
  }
  outsideRepairInfo.formInfo.data.assetId = row.assetId
  outsideRepairInfo.formInfo.data.orderId = row.id
  selectMaintenanceProvider.query.orgId = row.orgId

  outsideRepairInfo.formInfo.data.maintainChannel = row.maintainChannel

  outsideRepairInfo.formInfo.data.assetName = row.assetName
  outsideRepairInfo.formInfo.data.requireCompleteTime = row.expectCompleteTime

  if (row.assetId && row.assetId !== -2) {
    getAssetById(row.assetId).then((res) => {
      if (res && res.success) {
        if (res.data.maintenanceProviderName) {
          disabledMaintenanceName.value = true
        }
        outsideRepairInfo.formInfo.data.maintenanceName =
          res.data.maintenanceProviderName || ''
        outsideRepairInfo.formInfo.data.maintenanceId =
          res.data.maintenanceProvider === -2
            ? ''
            : res.data.maintenanceProvider

        proxy.$nextTick(() => {
          if (outsideRepairInfo.formInfo.ref) {
            outsideRepairInfo.formInfo.ref.clearValidate()
          }
        })
      }
    })
  } else {
    if (row.maintenanceName) {
      disabledMaintenanceName.value = true
    }
    outsideRepairInfo.formInfo.data.maintenanceName = row.maintenanceName || ''
    outsideRepairInfo.formInfo.data.maintenanceId =
      row.maintenanceId === -2 ? '' : row.maintenanceId
  }

  outsideRepairInfo.visible = true
  proxy.$nextTick(() => {
    if (outsideRepairInfo.formInfo.ref) {
      outsideRepairInfo.formInfo.ref.clearValidate()
    }
  })
}

function showMaintenanceDetail(row) {
  //跳转维修单详情
  maintenanceOrderDetailInfo.visible = true
  maintenanceOrderDetailInfo.id = row.id
}
function getDispatchUser() {
  getDispatchUserAll().then((res) => {
    if (res && res.success) {
      res.data.forEach((item) => {
        if (item.userId === proxy.$store.state.user.userInfo.user.id) {
          isDispatchUser.value = true
        }
      })
    }
  })
}
//删除附件
function uploadRemove(file, fileList) {
  registerInfo.formInfo.data.filePathList = fileList
}
function handleExceed() {
  proxy.$message.warning(` 只能上传 ${registerInfo.uploadInfo.limit} 个文件`)
}
function beforeProductUpload(file) {
  //验证文件格式
  let fileTypeArr = file.name.split('.')[file.name.split('.').length - 1]
  if (registerInfo.uploadInfo.fileType.indexOf(fileTypeArr) === -1) {
    proxy.$message.error(
      `文件格式不正确, 请上传 ${registerInfo.uploadInfo.fileType.join(
        ' / '
      )} 格式文件!`
    )
    return false
  }
  let file_type_list = proxy.$store.state.permission.dict['file_type_list']
  if (file_type_list && file_type_list.length) {
    let uploadType = file.name.split('.')[file.name.split('.').length - 1]
    let file_type_list_arr = []
    file_type_list.forEach((item) => {
      file_type_list_arr.push(item.code)
    })
    if (!String(file_type_list_arr).includes(uploadType)) {
      proxy.$message.error({
        message: `文件格式【${uploadType}】非白名单文件类型格式，不支持上传`,
        showClose: true,
        duration: 3500,
      })
      return false
    }
  }
  //验证文件大小
  const maxFileSize = file.size / 1024 / 1024 < registerInfo.uploadInfo.fileSize
  if (!maxFileSize) {
    proxy.$message.error(
      `上传文件大小不能超过${registerInfo.uploadInfo.fileSize}Mb！`
    )
    return false
  }
  //发生请求时打开加载动画
  registerInfo.uploadInfo.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  return true
}
//上传附件
function uploadAttachment(resp, file, fileList) {
  registerInfo.uploadInfo.loading.close()
  if (resp && resp.success) {
    file.filePath = resp.data[0]
    registerInfo.formInfo.data.filePathList = fileList
  }
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  registerInfo.uploadInfo.loading.close()
}
function handleCloseSendOrder() {
  sendOrderInfo.visible = false
}
function handleCloseRegister() {
  registerInfo.visible = false
}
function handleCloseFinish() {
  finishInfo.visible = false
}
function handleCloseEstimate() {
  estimateInfo.visible = false
}
function openRepairUserWindow() {
  const actualMaintenanceUser =
    sendOrderInfo.formInfo.data.actualMaintenanceUser
  if (
    actualMaintenanceUser &&
    actualMaintenanceUser != -2 &&
    sendOrderInfo.title === '改派'
  ) {
    selectRepairUserInfo.query.userIdNotIn = actualMaintenanceUser
  }
  selectRepairUserInfo.query.orgId =
    baseInfoList.data.maintainChannel === 1
      ? baseInfoList.data.maintenanceId === -2
        ? ''
        : baseInfoList.data.maintenanceId
      : ''
  selectRepairUserInfo.query.assetId =
    baseInfoList.data.assetId === -2 ? '' : baseInfoList.data.assetId
  selectRepairUserInfo.query.deptId =
    baseInfoList.data.useDeptId === -2 ? '' : baseInfoList.data.useDeptId
  selectRepairUserInfo.query.depotId =
    baseInfoList.data.depotId === -2 ? '' : baseInfoList.data.depotId
  selectRepairUserInfo.query.assetClassifyId =
    baseInfoList.data.classifyType === -2 ? '' : baseInfoList.data.classifyType
  selectRepairUserInfo.query.notAssetRepairType =
    baseInfoList.data.notAssetRepairType === -2
      ? ''
      : baseInfoList.data.notAssetRepairType
  selectRepairUserInfo.visible = true
}
function reminder() {
  reminderRepairOrder(baseInfoList.data.id).then((resp) => {
    if (resp && resp.success) {
      getDetails()
    }
  })
}
//派单
function sendOrder() {
  sendOrderInfo.formInfo.data = {}
  sendOrderInfo.visible = true
  sendOrderInfo.title = '派单'
  sendOrderInfo.formInfo.data.orderId = baseInfoList.data.id
  sendOrderInfo.formInfo.data.actualMaintenanceUser =
    baseInfoList.data.actualMaintenanceUser
  sendOrderInfo.formInfo.data.orderType = 53
  sendOrderInfo.formInfo.data.userId = baseInfoList.data.maintenanceUser
  sendOrderInfo.formInfo.data.requireCompleteTime =
    baseInfoList.data.expectCompleteTime
  selectRepairUserInfo.checkedRowList = []
  proxy.$nextTick(() => {
    sendOrderInfo.formInfo.ref.clearValidate()
  })
}
//改派
function updateSendOrder() {
  sendOrderInfo.formInfo.data = {}
  sendOrderInfo.visible = true
  sendOrderInfo.title = '改派'
  sendOrderInfo.formInfo.data.actualMaintenanceUser =
    baseInfoList.data.actualMaintenanceUser
  sendOrderInfo.formInfo.data.orderId = baseInfoList.data.id
  sendOrderInfo.formInfo.data.orderType = 53
  sendOrderInfo.formInfo.data.userId = baseInfoList.data.pendAcceptUser
  sendOrderInfo.formInfo.data['requireCompleteTime'] =
    baseInfoList.data.requireCompleteTime
  sendOrderInfo.formInfo.data['dispatchDescribe'] =
    baseInfoList.data.dispatchDescribe
  selectRepairUserInfo.checkedRowList = []
  proxy.$nextTick(() => {
    sendOrderInfo.formInfo.ref.clearValidate()
  })
}
//选择维修人员
function selectRepairUserCallBack(row) {
  if (row) {
    sendOrderInfo.formInfo.data['acceptUser'] = row.userId
    sendOrderInfo.formInfo.data['acceptUserName'] = row.name
  } else {
    sendOrderInfo.formInfo.data['acceptUser'] = ''
    sendOrderInfo.formInfo.data['acceptUserName'] = ''
  }

  if (row && row.length) {
    selectRepairUserInfo.checkedRowList = row
    const userIds = []
    const userNames = []
    row.forEach((item) => {
      userIds.push(item.userId)
      userNames.push(item.name)
    })
    sendOrderInfo.formInfo.data['acceptUser'] = userIds.join(',')
    sendOrderInfo.formInfo.data['acceptUserName'] = userNames.join(',')
  } else {
    selectRepairUserInfo.checkedRowList = []
    sendOrderInfo.formInfo.data['acceptUser'] = ''
    sendOrderInfo.formInfo.data['acceptUserName'] = ''
  }
}
//派单保存
function saveSendOrder() {
  sendOrderInfo.formInfo.data.dispatchType = 0
  sendOrderInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      if (sendOrderInfo.title === '派单') {
        dispatchRepairOrder(sendOrderInfo.formInfo.data).then((resp) => {
          if (resp && resp.success) {
            getDetails()
          }
          sendOrderInfo.visible = false
        })
      } else {
        updateDispatchRepairOrder(sendOrderInfo.formInfo.data).then((resp) => {
          if (resp && resp.success) {
            getDetails()
          }
          sendOrderInfo.visible = false
        })
      }
    }
  })
}
//处理登记
function handleRegister() {
  registerInfo.formInfo.data = {}
  registerInfo.visible = true
  registerInfo.formInfo.data.dealUser = proxy.$store.state.user.userInfo.user.id
    ? proxy.$store.state.user.userInfo.user.id
    : ''
  registerInfo.formInfo.data.dealUserName = proxy.$store.state.user.userInfo
    .user.name
    ? proxy.$store.state.user.userInfo.user.name
    : ''
  registerInfo.formInfo.data.orderId = baseInfoList.data.id
  registerInfo.formInfo.data.filePathList = []
  registerInfo.uploadInfo.fileList = []
  registerInfo.formInfo.data.orderType = 53
  proxy.$nextTick(() => {
    registerInfo.formInfo.ref.clearValidate()
  })
}
//处理登记保存
function saveRegister() {
  registerInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      repairDealAffair(registerInfo.formInfo.data).then((resp) => {
        if (resp && resp.success) {
          getDetails()
        }
        registerInfo.visible = false
      })
    }
  })
}
//完工
function finish() {
  finishInfo.formInfo.data = {
    completeTime: moment(new Date()).format('YYYY-MM-DD HH:mm'),
  }
  finishInfo.visible = true
  finishInfo.formInfo.data.id = baseInfoList.data.id
  proxy.$nextTick(() => {
    finishInfo.formInfo.ref.clearValidate()
  })
}
//完工保存
function saveFinish() {
  finishInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      completeDealRepairOrder(finishInfo.formInfo.data).then((resp) => {
        if (resp && resp.success) {
          getDetails()
        }
        finishInfo.visible = false
      })
    }
  })
}
//取消完工
function cancelFinish() {
  cannelRepairOrder(baseInfoList.data.id).then((resp) => {
    if (resp && resp.success) {
      getDetails()
    }
  })
}
//评价
function estimate() {
  estimateInfo.formInfo.data = {}
  estimateInfo.visible = true
  estimateInfo.formInfo.data.id = baseInfoList.data.id
}
//评价保存
function saveEstimate() {
  confirmRepairOrder(estimateInfo.formInfo.data).then((resp) => {
    if (resp && resp.success) {
      getDetails()
    }
    estimateInfo.visible = false
  })
}

function handleClick(tab) {
  const name = tab.paneName
  if (name == 'first') {
    getDealList()
  } else if (name == 'second') {
    getDispatchList()
  } else if (name == 'third') {
    getMaintenanceList()
  } else if (name == 'fourth') {
    getMountingsUseTableList()
  }
}
function handleTabClick(tab) {
  const name = tab.paneName
  if (name == 'third') {
    getAffairList()
  }
}

function modifyCallback() {
  getDetails()
}

function printAssetCode() {
  const data = []
  data.push(baseInfoList.data.id)
  assetCodePrint(data).then((res) => {
    if (res && res.success) {
      printerInfo.visible = true
      printerInfo.data = res.data
    }
  })
}
// 撤销
function revoke() {
  const data = []
  data.push(baseInfoList.data.id)
  revokeRepairOrder(data).then((resp) => {
    if (resp && resp.success) {
      getDetails()
    }
  })
}

function edit() {
  modifyInfo.value.id = baseInfoList.data.id
  modifyInfo.value.title = '修改验收单'
  modifyInfo.value.visible = true
  // emit('returnUpdate', baseInfoList.data.id)
}

// 按钮审批原因弹窗
function btnFlow(code) {
  const row = baseInfoList.data
  const currentBtnFlow = {
    title: '',
    api: null,
  }
  if (code === 'approve') {
    currentBtnFlow.api = approvedRepairOrder
    const data = {
      orderId: row.id,
    }
    currentBtnFlow.api(data).then((resp) => {
      if (resp && resp.success) {
        getDetails()
      }
    })
    return
  } else if (code === 'reject') {
    currentBtnFlow.title = '驳回'
    currentBtnFlow.api = rejectRepairOrder
  } else if (code === 'refuse') {
    currentBtnFlow.title = '拒绝'
    currentBtnFlow.api = refuseRepairOrder
  }
  proxy
    .$prompt('请输入' + currentBtnFlow.title + '理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: currentBtnFlow.title + '理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderId: row.id,
        checkOpt: value,
      }
      currentBtnFlow.api(data).then((resp) => {
        if (resp && resp.success) {
          getDetails()
        }
      })
    })
}
// 撤回
function recall() {
  recallRepairOrder([baseInfoList.data.id]).then((res) => {
    if (res && res.success) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      getDetails()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
// 销审
function salesReview() {
  cancelCheckRepairOrder([baseInfoList.data.id]).then((res) => {
    if (res && res.success) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      getDetails()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
function submit() {
  const params = {
    // flowTaskCommentDto和processDefinitionKey为审批流程需要传递的参数
    flowTaskCommentDto: { approvalType: 'submit' },
    processDefinitionKey: 'repairApply',
    orderId: baseInfoList.data.id,
  }
  submitRepairOrder(params).then((res) => {
    if (res && res.success) {
      getDetails()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
function exportExcel() {
  exportAssetCardDetail(customFilterInfo.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'repairApply',
    orderId: props.id,
    orderNo: baseInfoList.data.orderNo,
    deptId: baseInfoList.data.repairDeptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: props.id,
            orderNo: baseInfoList.data.orderNo,
          },
          data: {},
        })
      }
    }
  })
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: props.id,
      orderNo: baseInfoList.data.orderNo,
    },
    data: {},
  })
  popoverVisible.value = false
}

function getPrintData(temp) {
  let params = {
    customizeDto: customFilterInfo.query,
  }
  getAssetCardPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}

function handlePrinterCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.data, printer)
  }
  printerInfo.visible = false
}
function returnBack() {
  showDialog.value = false
  emit('returnBack', false)
}

// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function getDealList() {
  setTimeout(() => {
    dealInfo.refresh = Math.random()
  }, 0)
}
function getMountingsUseTableList() {
  setTimeout(() => {
    mountingsUseTableInfo.refresh = Math.random()
  }, 0)
}
function getAffairList() {
  orderOpAffairAll(affairTableInfo.query).then((resp) => {
    if (resp && resp.success) {
      affairTableInfo.data = resp.data
    }
  })
  // affairTableInfo.refresh = Math.random();
}
function getDispatchList() {
  setTimeout(() => {
    dispatchTableInfo.refresh = Math.random()
  }, 0)
}

function getDetails() {
  getRepairOrderById(props.id).then((resp) => {
    if (resp && resp.success) {
      repairPriceSlotInfoList.value.data.estimateAmount =
        resp.data.estimateAmount
      repairPriceSlotInfoList.value.data.appraisalContent =
        resp.data.appraisalContent
      tableInfoParts.value.data = resp.data.repairPartsEstimateList
      baseInfoList.data = resp.data
      if (resp.data.isRepairName) {
        estimateInfoList.data = resp.data
      }
      repairInfoList.data = resp.data
      noMaintenanceNameInfoList.data = resp.data
      finishInfoList.data = resp.data
      basicInfoList.data = resp.data
      if (resp.data.assetStatus === 1) {
        showFieldListItem1(true, 'useDeptName')
        showFieldListItem1(false, 'depotName')
        showFieldListItem2(true, 'useDeptName')
        showFieldListItem2(false, 'depotName')
      } else if (resp.data.assetStatus === 3) {
        showFieldListItem1(false, 'useDeptName')
        showFieldListItem1(true, 'depotName')
        showFieldListItem2(false, 'useDeptName')
        showFieldListItem2(true, 'depotName')
      }
      changeRepairType(resp.data)
      getDealList()
      getDispatchList()
      getMaintenanceList()
      getAffairList()
      getMountingsUseTableList()
    }
  })
}
function changeRepairType(data) {
  let fieldList = repairInfoList.fieldList
  if (data.maintainChannel === 1) {
    //维保商显示
    fieldList = repairInfoList.fieldList
  } else if (data.maintainChannel === 2) {
    //维保商隐藏
    fieldList = noMaintenanceNameInfoList.fieldList
  }
  if (data.repairType == 2) {
    // attrFieldListItem(fieldList, 'show', true, 'depotName')
    // attrFieldListItem(fieldList, 'show', true, 'useDeptName')
    if (data.repairType === 2) {
      showFieldListItem1(true, 'notAssetRepairTypeValue')
      showFieldListItem2(true, 'notAssetRepairTypeValue')
      showFieldListItem1(false, 'depotName')
      showFieldListItem2(false, 'depotName')
      showFieldListItem1(false, 'classifyTypeValue')
      showFieldListItem2(false, 'classifyTypeValue')
    }
  }
}
function attrFieldListItem(fieldList, attr, attrVal, nameValue) {
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item[attr] = attrVal
    }
  })
}

function showFieldListItem1(show, nameValue) {
  let fieldList = noMaintenanceNameInfoList.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
function showFieldListItem2(show, nameValue) {
  let fieldList = repairInfoList.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
function getMaintenanceList() {
  setTimeout(() => {
    maintenanceTableInfo.refresh = Math.random()
  }, 0)
}
//选择设备
function addData() {
  selectPartsObj.value.query.id.value = null
  if (tableInfoParts.value.data.length) {
    selectPartsObj.value.query.id.value = tableInfoParts.value.data
      .map((item) => item.productId)
      .toString()
  }
  selectPartsObj.value.visible = true
}
//删除项目
function removeData(selectRow = undefined) {
  if (selectRow) {
    tableInfoParts.value.data = tableInfoParts.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfoParts.value.data = tableInfoParts.value.data.filter(
          (row) => !tableInfoParts.value.selections.includes(row)
        )
      })
  }
}
//单价
function changePrice(e, row, str) {
  console.log(e)
  if (str === 'qty') {
    row.sumAmount = proxy.$fn.accMul(e, row.price)
    // row.sumAmount = proxy.$fn.TripartiteMethodAsset(e * row.price);
  } else if (str === 'price') {
    row.sumAmount = proxy.$fn.accMul(e, row.qty)
    // row.price = e;
    // row.sumAmount = proxy.$fn.TripartiteMethodAsset(e * row.qty);
  }
}
// 触发事件
function handleEventParts(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfoParts.value.selections = [...data]
      break
  }
}
function callBackAccessories(data) {
  if (data.length) {
    data.forEach((item) => {
      let obj = {
        productId: item.id,
        productName: item.commonName,
        price: item.referencePrice,
        ...item,
      }
      obj.qty ? '' : (obj.qty = 1)
      obj.sumAmount = proxy.$fn.accMul(obj.qty, obj.price)
      tableInfoParts.value.data.push(obj)
    })
    selectPartsObj.value.visible = false
  }
}
defineExpose({
  getFlowFormInfo,
  submitForm,
})
</script>
<style scoped lang="scss">
:deep(.el-tabs__header) {
  padding: 0 2px !important;
  box-sizing: border-box;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px !important;
}
.model-panel-left {
  width: 73%;
  float: left;
  margin-right: 10px;
}
.model-panel-right {
  width: 25%;
}
.i-more-disabled {
  cursor: not-allowed;
}
.i-more {
  background-color: #ffffff;
  cursor: pointer;
  height: 26px;
}
</style>
